package com.zerox.controller;

import com.alibaba.fastjson.JSON;
import com.zerox.domain.TableVo;
import com.zerox.pojo.SysUser;
import com.zerox.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/sysUser")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/SelectYongHu")
    @ResponseBody
    public void SelectYongHu(Model model, HttpServletResponse response, Integer page, Integer limit) throws IOException {
        List<SysUser> sysUserList = sysUserService.list((page - 1) * limit, limit);
        TableVo tableVo = new TableVo(0, 2, sysUserList, "");
        String json = JSON.toJSONString(tableVo);
        response.getWriter().print(json);
    }

    @GetMapping("toUser")
    public String toUser() {
        return "sysUser/YongHu";
    }

    @GetMapping("/view/{user_id}")
    public String view(Model model, @PathVariable Integer user_id) {
        SysUser sysUser = sysUserService.selectByUser_id(user_id);
        model.addAttribute("sysUser", sysUser);
        return "view";
    }

    @GetMapping("/update/{user_id}")
    public String Update(Model model, HttpSession session, @PathVariable Integer user_id) {
        SysUser sysUser = sysUserService.selectByUser_id(user_id);
        session.setAttribute("userId", user_id);
        model.addAttribute("sysUser", sysUser);
        return "update";
    }

    @PostMapping("/update")
    public String update(Model model, HttpSession session, SysUser sysUser, BindingResult bindingResult) {
        Integer userId = (Integer) session.getAttribute("userId");
        sysUser.setUser_id(userId);
        int result = sysUserService.update(sysUser);
        if (result > 0) {
            return "YongHu";
        }
        model.addAttribute("errorMsg", "修改失败");
        return "update";
    }

    @GetMapping("/delete/{user_id}")
    @ResponseBody
    public String delete(@PathVariable Integer user_id) {
        int result = sysUserService.delete(user_id);
        return result > 0 ? "true" : "false";
    }
}